import { ipcRenderer, remote } from "electron";

const { Menu, MenuItem, dialog } = remote;
ipcRenderer.on('action', (event, arg: string) => {
    //alert(arg);
    switch (arg) {
        case 'import':
            $("#importAcc").modal("show");
            break;
        case 'imports': //打开文件
            const files = remote.dialog.showOpenDialog(remote.getCurrentWindow(), {
                filters: [
                    { name: "Text Files", extensions: ['txt', 'csv'] },
                    { name: 'All Files', extensions: ['*'] }],
                properties: ['openFile']
            });
            if (files) {
                ipcRenderer.send("imports", files[0]);
            }

            break;

        case 'exiting':

            ipcRenderer.sendSync('exit');
            break;

        case "deleteAll": {
            $("#accPanels .tab-pane:not(.template)").remove();
            $("#accTabs .nav-item:not(.template)").remove();
        } break;
    }
});
ipcRenderer.on('init', (event, user: string, isok: boolean) => {
    //alert(arg);
    if (getPanel(user) == null)
        addItem($("#accPanels .template"), { user: user });
    if (getTab(user) == null)
        $("a", addItem($("#accTabs .template"), { user: user })).click();

    onMessage(user, "初始化完成");
});
ipcRenderer.on('sms', (event, user: string) => {
    //alert(arg);
    if ($("#smsDlg-" + user).length <= 0) {
        let html = template("temp-sms", { user: user });
        $("#modelContainer").append($(html));
        $("#smsDlg-" + user).modal("show");
    }
    $("#smsDlg-" + user + " .sms").val("");
    $("#smsDlg-" + user + " .retrysms").attr("disabled", "disabled");
    setTimeout(function () {
        $("#smsDlg-" + user + " .retrysms").removeAttr("disabled");
    }, 65 * 1000)
    onMessage(user, "等待输入手机验证码");
});
ipcRenderer.on('smsresult', (event, user: string, isok: boolean) => {
    if (isok) {
        $("#smsDlg-" + user).modal("hide");
        $("#smsDlg-" + user).remove();
        onMessage(user, "验证码验证成功");
    } else {
        //因为不知懂重拾，所以不需要删除
        $("#smsDlg-" + user + " .msg").text("验证码验证失败");
        onMessage(user, "验证码验证失败");
    }

});
ipcRenderer.on('loginok', (event, user: string, userinfo: {
    certStatus: string,
    certTp: string,
    cntryCode: string,
    eduStatus: string,
    encryptCdhdUsrId: string,
    faceRecgCert: string,
    faceRecgLoginSwitch: string,
    hceUserId: string,
    loginMobile: string,
    loginName: string,
    maskCertId: string,
    overSeaStatus: string,
    realName: string,
    respCode: string,
    respMsg: string,
    supDownloadBill: string,
    urid: string,
    welcomeWord: string,
    userSwitchs: {
        state: string,
        switchName: string
    }[]
}) => {
    //alert(arg);
    let panel = getPanel(user);
    let _userinfo = $(".userinfo", panel)
    let html = template("temp-userinfo", userinfo);

    _userinfo.html(html);
    $(".retryCard", panel).show();
    onMessage(user, "登录成功");
});
ipcRenderer.on('loginerror', (event, user: string, errmsg: string) => {
    //alert(arg);

    onMessage(user, errmsg, true);
});
ipcRenderer.on('cardinitok', (event, user: string, cardinfo: {
    certificate: string;//收款码
    isRealName: boolean,
    orderId: string,
    cardList: {
        bank: string,
        canPay: boolean,
        cardType: string,
        pan: string,
        virtualCardNo: string
        color: string,
        iconRelUrl: string,
    }[];
}, qrbase64: string) => {
    //alert(arg);
    let panel = getPanel(user);
    let _cardinfo = $(".cardinfo", panel)
    let html = template("temp-cardinfo", Object.assign({}, cardinfo, { qrcode: "data:image/png;base64," + qrbase64 }));
    _cardinfo.html(html);
    onMessage(user, "卡片信息获取完成");
});
ipcRenderer.on('cardiniterr', (event, user: string, errmsg: string) => {
    //alert(arg);
    onMessage(user, errmsg, true);

});
function onMessage(user: string, msg: string, iserr: boolean = false) {
    let panel = getPanel(user);
    if (iserr) {
        $(".msg", panel).addClass("err")
    } else {
        $(".msg", panel).removeClass("err")
    }
    $(".msg", panel).text(msg)

}
ipcRenderer.on('neworder', (event, user: string, orderdata: {
    orderId: string;
    time: string;
    amount: string;
    currency: string;
    reciveCard: string;
    payInfo: string;
    desc: string;
}) => {
    //alert(arg);
    let panel = getPanel(user);
    let _orderlist = $("#orders", panel)
    let html = template("temp-order", orderdata);
    _orderlist.prepend($(html));
    if ($("tr", _orderlist).length > 30) {
        $("tr:last-child", _orderlist).remove();
    }
    onMessage(user, "运行中");
});
function getTab(user: string) {

    let tab = $("#accTabs #tab-" + user)
    if (tab.length <= 0) return null;
    return tab;
}
function getPanel(user: string) {

    let panel = $("#accPanels #panel-" + user);
    if (panel.length <= 0) return null;
    return panel;


}

function addItem(temp, obj) {
    var t = $(temp).clone();
    t.removeClass("template");
    let html = t[0].outerHTML;
    for (let key in obj) {
        let r = new RegExp("\\[\\[\\$" + key + "\\]\\]", "g")
        html = html.replace(r, obj[key]);
    }

    t = $(html);
    $(temp).parent().append(t);
    return t
}
jQuery(document).ready(() => {
    $("#importAcc form").submit(function () {
        let pwd = $("#importAcc #pwd").val()
        let name = $("#importAcc #name").val();
        if ($("#accPanels #panel-" + name).length > 0) {
            alert("该账号已经在运行中");
            return;
        }
        ipcRenderer.send("import", name, pwd);
        $("#importAcc").modal("hide");
        return false;
    });
    $("#accPanels").delegate(".toolbar .deleteBtn", "click", function () {
        let user = $(this).parents(".tab-pane").attr("id").replace("panel-", "");
        let panel = getPanel(user);
        let tab = getTab(user);
        ipcRenderer.send("delete", user);

        tab.remove();
        panel.remove();
    })
    $("#accPanels").delegate(".toolbar .retryCard", "click", function () {
        let user = $(this).parents(".tab-pane").attr("id").replace("panel-", "");

        ipcRenderer.send("retryCard", user);

    })
    $("#modelContainer").delegate(".retrysms", "click", function () {
        let user = $(this).parents(".modal").attr("id").replace("smsDlg-", "");
        ipcRenderer.send("retrySms", user);
    })

    $("#modelContainer").delegate(".verify", "click", function () {
        let user = $(this).parents(".modal").attr("id").replace("smsDlg-", "");
        // console.log($("#sms", $(this).parents(".modal")).val());
        ipcRenderer.send("verifySms", user, $("#sms", $(this).parents(".modal")).val());

    })
})
